package com.globox.servlet;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import utils.Theater;

public class GloboxServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -3207598127933501658L;

	private static final String LIST_THEATERS = app_srv_interface.IGlobox.LIST_THEATERS;

	private Integer clientID = -1;

	private String appSrvPort = IConstants.appSrvPort;

	private String appSrvHost = IConstants.appSrvHost;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// Use "request" to read incoming HTTP headers (e.g. cookies)
		// and HTML form data (e.g. data the user entered and submitted)

		// Use "response" to specify the HTTP response line and headers
		// (e.g. specifying the content type, setting cookies).

		PrintWriter out = response.getWriter();
		String query = request.getParameter("query");
		String header = IConstants.HEADER;
		// out.write("query=" + query);
		// open a socket to app server and get results
		if (query != null && !query.equalsIgnoreCase(""))
			try {
				List<Theater> rslt = searchTheaters(query, out);
				HttpSession session = request.getSession(true);

				if (session != null) {
					clientID = (Integer) session.getAttribute("MY_UNIQUE_ID");
					if (clientID == -1 || clientID == 0) {
						// regenerate
						clientID = new Random().nextInt(IConstants.MAX_CLIENTS);
						session.setAttribute("MY_UNIQUE_ID", clientID);
					}
				}

				header = header.replace("{{uniqueId}}", clientID + "");

				if (rslt != null && rslt.size() > 0) {
					header += "<p style=\"color:gray; font-weight:bold;\">Found ("
							+ rslt.size() + ") results" + "</p><br />";

					header += "<table>";

					for (Theater t : rslt) {
						String tName = t.getName();
						String link = "<a href=\"/globox-client/browse-sits?theater="
								+ tName + "\">View</a>";

						header += "<tr><td>" + tName + "</td><td>" + link
								+ "</td></tr>";
					}

					header += "</table></body></html>";
				} else {
					header += "<p style=\"align:right;\">No results found for query "
							+ query + "</p></body></html>";
				}

				out.write(header);
			} catch (NumberFormatException e) {
				out.write("NumberFormatException parsing app srv port." + e
						+ "<br />");
				e.printStackTrace();
			} catch (UnknownHostException e) {
				out.write("UnknownHostException connecting to app srv." + e
						+ "<br />");
				e.printStackTrace();
			} catch (IOException e) {
				out.write("IOException in communication with app srv port." + e
						+ "<br />");
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				out.write("ClassNotFoundException in communication with app srv port."
						+ e + "<br />");
				e.printStackTrace();
			} catch (Exception e) {
				out.write("Exception " + e + "<br />");
				e.printStackTrace();
			}
	}

	private List<Theater> searchTheaters(String query, PrintWriter out)
			throws Exception {

		if (!appSrvHost.equalsIgnoreCase("")
				&& !appSrvPort.equalsIgnoreCase("")) {

			Socket s = new Socket(appSrvHost, Integer.parseInt(appSrvPort));

			ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
			ObjectInputStream ois = new ObjectInputStream(s.getInputStream());

			oos.writeObject(LIST_THEATERS);
			oos.flush();

			oos.writeObject(query);
			oos.flush();

			// out.write("before getting response" + "<br />");

			@SuppressWarnings("unchecked")
			List<Theater> results = (List<Theater>) ois.readObject();

			return results;
		} else {
			throw new Exception("Invalid settings-call for server");
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// Use "request" to read incoming HTTP headers (e.g. cookies)
		// and HTML form data (e.g. data the user entered and submitted)

		// Use "response" to specify the HTTP response line and headers
		// (e.g. specifying the content type, setting cookies).

		// PrintWriter out = response.getWriter();
		// String param = request.getParameter("tbSearch");
		// out.write("query=" + param);
		// Use "out" to send content to browser
	}
}